﻿using System.Linq;
using System.Text;
using MRGSP.SurveyMaster.Core;
using MRGSP.SurveyMaster.Core.Model;
using MRGSP.SurveyMaster.Core.Service.Utils;

namespace MRGSP.SurveyMaster.Service.Utils
{
    public class GridCreateBuilder : IQuestionBuilder
    {
        public string Build(Question q)
        {
            var b = new StringBuilder();
                        
            b.Append(
                string.Format(
                    @"<div id='qwrap{0}'><div id='util{0}' class='util'>{1}{2}{3}",
                          q.Id,
                          LinkBuilder.Build(LinkType.Add, "addRow", q.Id),
                          LinkBuilder.Build(LinkType.Edit, "editRoot", q.Id),
                          LinkBuilder.Build(LinkType.Remove, "deleteQuestion", q.Id)
                          ));

            if (q.HasChildren())
                b.Append(LinkBuilder.Build(LinkType.Addcolumn, "addColumn", q.Id));

            b.Append("</div>");
            b.Append(HtmlGeneratorFactory.Generate(q));

            b.Append("<table><thead><tr><th>&nbsp;</th>");

            if (q.HasChildren())
            {
                var firstChild = q.Children.First();

                foreach (var gridColumn in firstChild.Children)
                {
                    b.Append(string.Format(
                        @"<th><div id='qwrap{1}'><div id='util{1}' class='util'>{2}{3}</div>{0}</div></th>",
                        HtmlGeneratorFactory.Generate(gridColumn), 
                        gridColumn.Id,
                        LinkBuilder.Build(LinkType.Add, "addCellElement", gridColumn.Id),
                        LinkBuilder.Build(LinkType.Remove, "deleteColumn", gridColumn.Id)
                        ));
                }
            }

            b.Append("</tr></thead>");
            var ch = q.Children.Aggregate(string.Empty, (current, row) 
                => current + string.Format("<tr>{0}</tr>", QuestionCreateBuilder.Get(ControlType.GridRow).Build(row)));

            b.Append(ch);
            b.Append("</table></div>");
            return b.ToString();
        }
    }
}